﻿using System.IO;
using System.Text;

namespace ShareHelper
{
    /// <summary>
    /// 获取TXT文件编码
    /// </summary>
    public static class EncodingType
    {
        /// <summary>
        /// 给定文件的路径，读取文件的二进制数据，判断文件的编码类型
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>文件的编码类型</returns>
        public static Encoding GetType(string path)
        {
            using (var fs = new FileStream(path, FileMode.Open))
                return GetType(fs);
        }

        /// <summary>
        /// 通过给定的文件流，判断文件的编码类型
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns>文件的编码类型</returns>
        public static Encoding GetType(FileStream fs)
        {
            if (fs?.Length > 0)
            {
                var data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                if (data[0] == 254 && data[1] == 255)
                {// big endian unicode
                    return Encoding.BigEndianUnicode;
                }
                else if (data[0] == 255 && data[1] == 254)
                {// unicode
                    return Encoding.Unicode;
                }
                else if ((data[0] == 239 && data[1] == 187) || IsUTF8Bytes(data))
                {// unicode
                    return Encoding.UTF8;
                }
            }
            return Encoding.Default;
        }

        /// <summary>
        /// 判断是否是不带 BOM 的 UTF8 格式
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
            byte curByte; //当前分析的字节.
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
                return false; ;
            return true;
        }
    }
}